AI.Widget = Event.$extend({
 	default:{
 		widthcol:6,
 		panelClass:'',
 		bgcolr:'bg-light',
 		height:'auto',
 		padding:'15px',
 		containerId:""
 	},
	 __init__ : function(options) {
	    this.options= $.extend(true, this.default, options);
	 	 this.init( this.options);
	 	 
	 },
	 sparkGraph:function(selecter){
	 	  ai.loadWidget("sparkline");
			var sr, sparkline = function($re){
			$(".sparkline").each(function(){
			var $data = $(this).data();
			if($re && !$data.resize) return;
			($data.type == 'pie') && $data.sliceColors && ($data.sliceColors = eval($data.sliceColors));
			($data.type == 'bar') && $data.stackedBarColor && ($data.stackedBarColor = eval($data.stackedBarColor));
			$data.valueSpots = {'0:': $data.spotColor};
			$(this).sparkline('html', $data);
		});
	  }
	 },
	 easypie :function(selecter){
	  
	 	//ai.loadWidget("piechart");
	   this.body.find(selecter).each(function(){
		var $this = $(this), 
		$data = $this.data(), 
		$step = $this.find('.step'), 
		$target_value = parseInt($($data.target).text()),
		$value = 0;
		$data.barColor || ( $data.barColor = function($percent) {
	        $percent /= 100;
	        return "rgb(" + Math.round(200 * $percent) + ", 200, " + Math.round(200 * (1 - $percent)) + ")";
	    });
		$data.onStep =  function(value){
			$value = value;
			$step.text(parseInt(value));
			$data.target && $($data.target).text(parseInt(value) + $target_value);
		}
		$data.onStop =  function(){
			$target_value = parseInt($($data.target).text());
			$data.update && setTimeout(function() {
		        $this.data('easyPieChart').update(100 - $value);
		    }, $data.update);
		}
			$(this).easyPieChart($data);
		});
	},
	 circliful:function(selecter){
		if (typeof circliful =="undefined"){
			ai.loadWidget("circliful");
		};
		this.body.find(selecter).circliful();
	 },
	 echarts:function(options){
	 	var adaterSimpleChart= function (store,xfield,valuefield){///根据store计算适配的数据 ,line,bar,
	 		var categories = [];
			var seriesData = [];
			for (var i = 0; i < store.getCount(); i++) {
			        var r = store.getAt(i);
			        var catVal = r.get(xfield);
			        var ind = categories.indexOf(catVal);
			        if(ind==-1){
			        	  categories.push(r.get(xfield));
			             seriesData.push(r.get(valuefield));
			        }else{
			        	 seriesData[i]+=r.get(valuefield);
			        }
			 };
			 return {categories:categories,seriesData:seriesData};
		};
		var config;
		var chartOption = {
   		 title: {
       		 text: '数据库情况',
        		subtext: '数据库空间情况'
    	},
    tooltip: {
        trigger: 'axis',
        axisPointer: { // 坐标轴指示器，坐标轴触发有效
            type: 'shadow' // 默认为直线，可选为：'line' | 'shadow'
        } 
    },
    legend: {
        selectedMode: false,
        data: ['已用空间']
    },
    toolbox: {
        show: false,
        feature: {
            mark: {
                show: true
            },
            dataView: {
                show: true,
                readOnly: false
            },
            restore: {
                show: true
            },
            saveAsImage: {
                show: true
            }
        }
    },
    calculable: true,
    xAxis: [{
        type: 'category',
        data: ['Cosco', 'CMA', 'APL', 'OOCL', 'Wanhai', 'Zim']
    }],
    yAxis: [{
        type: 'value',
        boundaryGap: [0, 0.1]
    }],
    series: [{
        name: '已用空间',
        type: options.charttype||'line',
        //stack: 'sum',
        barCategoryGap: '50%',
        itemStyle: {
            normal: {
                color: 'tomato',
                barBorderColor: 'tomato',
                barBorderWidth: 6,
                barBorderRadius: 0,
                label: {
                    show: true,
                    position: 'insideTop'
                }
            }
        },
        data: [260, 200, 220, 120, 100, 80]
    } 
    ]
       };
		if(options.charttype=='bar'){
			config=adaterSimpleChart(options.store,options.xfield,options.valuefield);
		 
			chartOption.xAxis[0].data=config.categories;
			chartOption.series[0].data=config.seriesData;
			chartOption.legend.data[0]="我的空间"
		};
	   	var myChart1 = echarts.init(document.getElementById(options.containerId));
		myChart1.setOption(chartOption);
	},
	init:function(options){
		
	 var toolTpl='<span class="pull-right"> <a href="#edit" ><i class="fa fa-pencil fa-fw m-r-xs"></i></a> <a href="#"><i class="fa fa-plus fa-fw m-r-xs"></i></a> <a href="#"><i class="fa fa-times fa-fw"></i></a></span>';
	 var tpl='<div class="col-sm-'+options.widthcol+' portlet ui-sortable" >'+
		            '<section class="panel '+options.panelClass+' portlet-item" style="opacity: 1; z-index: 0">' +
		               '<header class="panel-heading"> '+options.title+toolTpl+'  </header> '+
		               '<div class="panel-body "  style="width:100%;height:'+options.height+';padding:'+options.padding+'"> </div>' +
		            '</section>'+
		          '</div>';
	   var containerId="body";
	   if(!options.containerId) containerId="body"
	   else  containerId =options.containerId;
	   	
	  var $container = $(tpl).appendTo($("#"+containerId));
	  this.body= $container.find('.panel-body');
	  if(this.create) this.create(options);
	 }
   });
   
   ai.widget.Caland= AI.Widget.$extend({///个人工作日历组件
   	  create:function(options){
   	  	var entryEl = $(' <div id="calendar" ></div>').appendTo(this.body);
      	console.log(this.body.html());	 
       var sql=  "select  task_id itemseq, task_name itemname,  remark content, eff_date st_date, '' et_date   from wf_task_list "
	   var taskStore= new AI.JsonStore({
			sql:sql,
			pageSize:-1,
			key:'itemseq',
			dataSource:'METADB'
		});
		var taskList=[];
		for(var i=0;i<taskStore.getCount();i++){
			 var r=taskStore.getAt(i);
			 var st=null,et=null;
			 if(r.get('ST_DATE')) st =r.get('ST_DATE') ;
			 if(r.get('ET_DATE')) et =r.get('ET_DATE') ;
			 var tmpDate=new Date().DateAdd('d',- parseInt(Math.random()*5));
			 st=(tmpDate).format('yyyy-mm-dd');
			 var tmpDate=new Date().DateAdd('d', parseInt(Math.random()*5));
			 et=(tmpDate).format('yyyy-mm-dd');
			 var eventItem={id:r.get('ITEMSEQ'),title:r.get('ITEMNAME'),start:st,end:et};
			 taskList.push(eventItem);
		};
		$('#calendar').attr("class","");
		$('#calendar').fullCalendar( 'destroy' ) ;
		$('#calendar').fullCalendar({
			header: {
				left: 'prev,next today',
				center: 'title',
				right: 'month,agendaWeek,agendaDay'
			},
			height: 450,
			monthNames:['一月','二月', '三月', '四月', '五月', '六月', '七月', '八月', '九月', '十月', '十一月', '十二月'],
			dayNames:['星期日', '星期一', '星期二', '星期三','星期四', '星期五', '星期六'],
			dayNamesShort:['星期日', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六'],
			buttonText:{ prev:'昨天', next:'明天', prevYear: '去年', nextYear: '明年', today:'今天', month:'月', week:'周', day:'日' },
			defaultDate: (new Date()).format("yyyy-mm-dd"),
			editable: true,
			eventLimit: true, // allow "more" link when too many events
			events:  taskList
		});
	 }
   });
   
   ai.widget.myInfo= AI.Widget.$extend({///我的信息
   	 create:function(options){
   	 	var myInfoHtml='<div class="clearfix text-center m-t"> <div class="inline"> <div class="easypiechart easyPieChart" data-percent="75" data-line-width="5" data-bar-color="#4cc0c1" data-track-color="#f5f5f5" data-scale-color="false" data-size="134" data-line-cap="butt" data-animate="1000" style="width: 104px; height: 84px; line-height: 84px;"> <div class="thumb-lg"> <img src="/'+contextPath+'/dacp-res/catalog/dataportal/images/face.png" class="img-circle" alt="..."> </div> <canvas width="134" height="134"></canvas></div> <div class="h4 m-t m-b-xs">${username}</div> <small class="text-muted m-b">${usercnname}</small> </div> </div>'
       +'<footer class="panel-footer bg-info text-center"> <div class="row pull-out"> <div class="col-xs-4"> <div class=""> <span class="m-b-xs h3 block text-white">${mytasknum}</span> <small class="text-muted">我的待办</small> </div> </div> <div class="col-xs-4 dk"> <div class=""> <span class="m-b-xs h3 block text-white">${mydevnum}</span> <small class="text-muted">我开发的表</small> </div> </div> <div class="col-xs-4"> <div class=""> <span class="m-b-xs h3 block text-white">${myduban}</span> <small class="text-muted">我的督办</small> </div> </div> </div> </footer>  ';
   	  
   	  var myinfo={username:_UserInfo.name,usercnname:_UserInfo.usercnname,mytasknum:11,mydevnum:203,myduban:2};
   	  $.template('myInfoTpl', myInfoHtml); 
   	  $.tmpl('myInfoTpl',myinfo).appendTo(this.body); 
      
	   this.easypie('.easypiechart');  
   	 }
  });
   
   ai.widget.ownerTeamsInfo= AI.Widget.$extend({///开通的平台信息
	   	 create:function(options){
	   		// this.body.addClass("bg-light lt");
	   	   var teamTpl=['  <div class="col-sm-4"> ',
	   	             '   <section class="panel panel-info"> ',
	   	          '   <header class="panel-heading">Hadoop平台</header>',
	   	          '    <ul class="list-group no-radius"> ',
	   	          '     <li class="list-group-item"> <span class="pull-right">480</span> <span class="label bg-primary">资源</span>CPU    <div class="slider slider-horizontal" style="width: 100px;"><div class="slider-track"><div class="slider-selection" style="left: 24.2424%; width: 50.5051%;"></div><div class="slider-handle round" style="left: 24.2424%;"></div><div class="slider-handle round" style="left: 74.7475%;">120</div></div><div class="tooltip top" style="top: -30px; left: 73.9394px;"><div class="tooltip-arrow"></div><div class="tooltip-inner">250 : 750</div></div><input type="text" class="slider form-control" value="" data-slider-min="10" data-slider-max="1000" data-slider-step="5" data-slider-value="[250,750]" id="sl2"></div>  </li> ',
	   	          '     <li class="list-group-item" style="padding-left: 55px;"> <span class="pull-right">45,000</span> <span class="label bg-primary"></span> 内存<div class="slider slider-horizontal" style="width: 100px;"><div class="slider-track"><div class="slider-selection" style="left: 24.2424%; width: 50.5051%;"></div><div class="slider-handle round" style="left: 24.2424%;"></div><div class="slider-handle round" style="left: 74.7475%;"></div></div><div class="tooltip top" style="top: -30px; left: 73.9394px;"><div class="tooltip-arrow"></div><div class="tooltip-inner">250 : 750</div></div><input type="text" class="slider form-control" value="" data-slider-min="10" data-slider-max="1000" data-slider-step="5" data-slider-value="[50,750]" id="sl3"></div>  </li> ',
	   	          '     <li class="list-group-item" style="padding-left: 55px;"> <span class="pull-right">45,000</span> <span class="label bg-primary"></span> 存储<div class="slider slider-horizontal" style="width: 100px;"><div class="slider-track"><div class="slider-selection" style="left: 24.2424%; width: 50.5051%;"></div><div class="slider-handle round" style="left: 24.2424%;"></div><div class="slider-handle round" style="left: 74.7475%;"></div></div><div class="tooltip top" style="top: -30px; left: 73.9394px;"><div class="tooltip-arrow"></div><div class="tooltip-inner">250 : 750</div></div><input type="text" class="slider form-control" value="" data-slider-min="10" data-slider-max="1000" data-slider-step="5" data-slider-value="[50,750]" id="sl3"></div>  </li> ',
	   	          '     <li class="list-group-item" style="padding-left: 55px;"> <span class="pull-right">rend-appuser</span> <span class="label bg-primary"></span> 账号   </li> ',
	   	          '     <li class="list-group-item"> <span class="pull-right">23,200</span> <span class="label bg-info">数据</span> 已申请数据 </li> ',
	   	          '     <li class="list-group-item" style="padding-left: 55px;"> <span class="pull-right">21,000</span> <span class="label bg-success"></span>私有的数据 </li> ',
	   	          '     <li class="list-group-item" style="padding-left: 55px;"> <span class="pull-right">15,000</span> <span class="label bg-light"></span> 已发布数据 </li> ',
	   	          '    </ul> ',
	   	          '   </section> ',
	   	          '  </div>'].join("");
	   	   
	   	 	var myTeamInfoHtml=teamTpl;
	   	  
	   	  var myinfo={username:_UserInfo.name,usercnname:_UserInfo.usercnname,mytasknum:11,mydevnum:203,myduban:2};
	   	  $.template('myInfoTpl', myTeamInfoHtml); 
	   	  $.tmpl('myInfoTpl',myinfo).appendTo(this.body); 
	   	  $.tmpl('myInfoTpl',myinfo).appendTo(this.body); 
	   	  $.tmpl('myInfoTpl',myinfo).appendTo(this.body); 
	   	  //$.tmpl('myInfoTpl',myinfo).appendTo(this.body);
	      this.bindHeadEvent();
	   	 },
	   	 bindHeadEvent:function(){
	   		this.body.parent().find(".panel-heading a").click(function(){
	   			alert($(this).attr("href"));
	   		})
	   	 }
	   	
	  });
   
   ai.widget.teamTools= AI.Widget.$extend({///团队开通的工具
	   	 create:function(options){
	   		 
	   	   var teamTpl=['<section class="panel panel-info portlet-item" style="opacity: 1; z-index: 0;"> ',
	   	         
	   	          '   <div class="list-group bg-white"> ',
	   	          '    <a href="#" class="list-group-item"> <i class="fa fa-fw fa-envelope"></i> Inbox </a> ',
	   	          '    <a href="#" class="list-group-item"> <i class="fa fa-fw fa-eye"></i> Profile visits </a> ',
	   	          '    <a href="#" class="list-group-item"> <i class="fa fa-fw fa-phone"></i> Call </a> ',
	   	          '    <a href="#" class="list-group-item"> <i class="fa fa-fw fa-comments-o"></i> Messages </a> ',
	   	          '    <a href="#" class="list-group-item"> <i class="fa fa-fw fa-bookmark"></i> Bookmarks </a> ',
	   	          '    <a href="#" class="list-group-item"> <i class="fa fa-fw fa-bell"></i> Notifications </a> ',
	   	          '   </div> ',
	   	          '   <footer class="panel-footer">  <a href="#" class="btn btn-default btn-xs"> <i class="fa fa-trash-o text-muted"></i> 开通更多 </a></footer>',
	   	          '  </section>'].join("");
	   	   
	   	 	var myTeamInfoHtml=teamTpl;
	   	  
	   	  var myinfo={username:_UserInfo.name,usercnname:_UserInfo.usercnname,mytasknum:11,mydevnum:203,myduban:2};
	   	  $.template('myInfoTpl', myTeamInfoHtml); 
	   	  $.tmpl('myInfoTpl',myinfo).appendTo(this.body); 

	   	 }
	   	
	  });
  ai.widget.myTaskInfo= AI.Widget.$extend({///我的待办信息
   	 create:function(options){
   	 	var mytask=[
   	 	{title:'你有1条待上线的计划',url:'/dacp/oltp/oltpPlanInfo.html'},
   	 	{title:'你有2条待测试的任务单',url:'/dacp/oltp/oltpPlanTest.html'},
   	 	{title:'你有1条待审批的任务单',url:'/dacp/oltp/oltpPlanUpLine.html'},
   	 	{title:'你有3条开发未完成的任务单',url:'/dacp/oltp/oltpPlanInfo.html'}
   	 	]
   	 	var tasktpl='<a href="#" ref="{url}" class="list-group-item"> <i class="fa fa-fw fa-comments-o"></i> {title} </a>';
   	 	var html='<div class="list-group bg-white">';
   	 	 for(var i=0;i<mytask.length;i++){
   	 	    html+=tasktpl.replace('{url}',mytask[i].url).replace('{title}',mytask[i].title);
   	 	  };
   	 	html+='</div> ';
   	 	var $list = $(html).appendTo(this.body);
   	    $("a",$list).click(function(){
   	    	 
   	    	ai.addTabSheet('myinfo','我的任务',$(this).attr('ref'));
   	    	return false;
   	    });
   	 	
   	 }
  });
  ai.widget.myApplyTaskInfo= AI.Widget.$extend({///我的待办信息
   	 create:function(options){
   	 	var store=ai.getJsonStore("select task_id,task_name,eff_date,state,state_date,curdutyer from wf_task_list where creater='"+_UserInfo.usercnname+"'");
   	 	
   	 	var $listEl=$('<div class="list-group bg-white"></div>').appendTo(this.body);
   	 	
   	 	var myApplyTaskInfo='<a href="#" ref="/dacp/oltp/oltpPlanInfo.html" class="list-group-item"> <i class="fa fa-fw fa-comments-o"></i> <b>${TASK_NAME}</b>,编号:${TASK_ID},当前状态${CURDUTYER},由${CURDUTYER}负责 </a>';
   	 	
   	  
        $.template('myApplyTaskInfoTpl', myApplyTaskInfo); 
        $.tmpl('myApplyTaskInfoTpl', store.root).appendTo($listEl); 
   	 	 
   	    $("a",$listEl).click(function(){
   	    	ai.addTabSheet('myinfo','我的任务',$(this).attr('ref'));
   	    	return false;
   	    });
   	 	
   	 }
  });
  ai.widget.dqSumInfo= AI.Widget.$extend({///系统质量公式
   	 create:function(options){
   	 	var testIem=[
           {code:'item-01',name:'正确性-脚本执行情况',value:''},
           {code:'item-02',name:'正确性-质量案例通过',value:''},
           {code:'item-03',name:'规范性-关键属性完整性',value:''},
           {code:'item-04',name:'规范性-命名规范性',value:''},
           {code:'item-05',name:'一致性-是否和元数据一致',value:''},
           {code:'item-06',name:'一致性-实例表是否完整',value:''},
           {code:'item-06',name:'一致性-逻辑模型与物理模型',value:''},
           {code:'item-06',name:'合理性-索引设置是否合理',value:''},
           {code:'item-06',name:'合理性-分区设置是否合理',value:''},
           {code:'item-06',name:'合理性-字段设置合理性',value:''},
           {code:'item-06',name:'性能-单步最大时长',value:''},
           {code:'item-06',name:'性能-总体时长',value:''}
           ];
           var html='<br><table class="table table-bordered">';
           for(var i=0;i<testIem.length;i++){
           	var item=testIem[i];
           	if(i==0) html+='<tr>'
           	else if((i % 3)==0) html+='</tr></tr>';
           	html+="<td class='bg-light dk'>"+item.name+'</td><td style="width:90px">'+(item.value||"--")+"</td>";
          };
          html+="</tr></table>";
        
          $(html).appendTo(this.body);
   	 }
  });
  ai.widget.NavBar= AI.Widget.$extend({///分类导航信息
	   	 create:function(options){
	   	 	var dataArray=[
	   	 	{title:'我是开发人员',class:'col-md-3',url:'/dacp/oltp/oltpPlanInfo.html',item:'选择团队,脚本开发,数据开发,模型开发,采集开发,分发开发,数据发布,上线调度'},
	   	    {title:'我是运维人员',class:'col-md-3',url:'/dacp/oltp/oltpPlanInfo.html',item:'上线,运行监控,质量监控,数据清理,下线'},
	   	 	{title:'我是团队管理员',class:'col-md-3',url:'/dacp/oltp/oltpPlanTest.html',item:'资源资源申请,数据资源申请,私有数据注册,数据上传,团队管理,数据发布'},
	   	 	{title:'我是平台管理员',class:'col-md-3',url:'/dacp/oltp/oltpPlanUpLine.html',item:'资源管理,租户管理,数据审批,租户资源评估'}
	   	 	]
	   	 	var htmltpl='<div class="{class}"><div class="bs-callout"><h4 class="page-header">{title}</h4>{items}</div></div>';
	   	 	var html="";
	   	 	for(var i=0;i<dataArray.length;i++){
	   	 		var data=dataArray[i];
	   	 		var itemHtml="";
	   	 		var items=data.item.split(",");
	   	 		for(var j=0;j<items.length;j++){
	   	 		  itemHtml+='<a href="#">'+items[j]+'</a>';
	   	 		};
	   	 	    var dataHtml=htmltpl.replace("{title}",data.title).replace("{class}",data.class).replace("{items}",itemHtml);
	   	 	    html+=dataHtml;
	   	 	}	  
	   	 	 
	   	 	 $(html).appendTo(this.body);
	   	 }
	  });
  ai.widget.sysHealth=AI.Widget.$extend({///系统健康度
   	 create:function(options){
   	 	var widgetView='<div class="circle" style="margin-left: auto;margin-right: auto;" data-dimension="250" data-text="35%" data-info="系统健康度" data-width="20" data-fontsize="38" data-percent="35" data-fgcolor="#61a9dc" data-bgcolor="#eee" data-fill="#ddd"></div>'
   	 	                        +'<div class="row"><div class="row text-center">'
	 	 	  					  +'		<div class="col-xs-6"><a> <span class="m-b-xs h3 block">30%</span> <small class="text-muted"> 健康度 </small></a></div>'
	 	 	  					  +'		<div class="col-xs-6"><a> <span class="m-b-xs h4 block">0</span> <small class="text-muted"> 总的模型数 </small></a></div>'
	 	 						  +' </div></div>';
   	 	 var widgetData={};
        $.template('widgetViewTpl', widgetView); 
       
        $.tmpl('widgetViewTpl',widgetData).appendTo(this.body); 
   	 	 this.circliful(".circle");
   	 }
  }); 
   ai.widget.sysItemHealth=AI.Widget.$extend({///系统健康度分项
   	 create:function(options){
 
   	 	var widgetView='<div class="chart" style="position:relative;float:left;>'
    							+	'<div class="percentage" data-percent="${percent}"><span>${percent}</span>%</div>'
    							+	'<div class="label">${title}</div>'
  								+'</div>';
  	    var widgetView ='<div class="inline" style="margin:20px">'
  	    					   + '<div class="easypiechart easyPieChart" data-percent="75" data-line-width="5" data-bar-color="#4cc0c1" data-track-color="#f5f5f5" data-scale-color="false" data-size="134" data-line-cap="butt" data-animate="1000" style="width: 100px; height: 100px; line-height: 100px;"> <div class="thumb-lg">  </div>  </div> <div class="h4 m-t m-b-xs"></div> <small class="text-muted m-b">系统管理员</small>'
  	    					   +'</div>';
		
   	 	 var widgetData=[{percent:20,title:'标准化'},{percent:20,title:'质量'},{percent:20,title:'安全'},{percent:20,title:'存储'},{percent:20,title:'架构'}];
   	 	 
        $.template('widgetViewTpl', widgetView); 
        
        $.tmpl('widgetViewTpl',widgetData).appendTo(this.body); 
   	 	 this.easypie(".easypiechart");
   	 }
  });
  ai.widget.dbspace=AI.Widget.$extend({///数据库表空间
   	 create:function(options){
   	 	 var spaceStore=ai.getJsonStore("select channel_name,value,last_year from kpi_total_daily where zb_code='K10021' and parent_channel_code='HB' and time_id='20121226'");
   	 	 var containerId = ai.guid();
   	 	 options.containerId=containerId;
   	 	 options.xfield="CHANNEL_NAME";
   	 	 options.valuefield="VALUE";
   	 	  //options.valuefield=[{fieldname:'VALUE',type:'line'},{fieldname:'LAST_YEAR',type:'line'}],
   	 	 //itemStyle: {normal: {areaStyle: {type: 'default'}}}
   	 	 options.charttype='bar';//line,
   	 	 options.store = spaceStore;
   	 	 this.body.attr("id",containerId);
   	 	  this.body.css("height","300px");
   	 	 this.echarts(options);
   	 }
  }); 